package main

import (
	"fmt"
	"net"
	"net/rpc"
)

type Goods struct {
}

type AddGoodsReq struct {
	Id      int
	Title   string
	Price   float32
	Content string
}

type AddGoodsRes struct {
	Success bool
	Msg     string
}

type GetGoodReq struct {
	Id int
}

type GetGoodRes struct {
	Success bool
	Msg     string
	Good    AddGoodsReq
}

func (g Goods) AddGoods(req AddGoodsReq, res *AddGoodsRes) error {
	fmt.Printf("执行增加 %v \n", req)

	*res = AddGoodsRes{
		Success: true,
		Msg:     "增加成功",
	}

	return nil
}

func (g Goods) GetGoods(req GetGoodReq, res *GetGoodRes) error {
	fmt.Printf("执行获取 %v \n", req)

	*res = GetGoodRes{
		Success: true,
		Msg:     "获取成功",
		Good: AddGoodsReq{
			Id:      12,
			Title:   "测试商品",
			Price:   100.0,
			Content: "测试商品内容",
		},
	}

	return nil
}

func main() {
	// 注册服务
	err := rpc.RegisterName("goods", new(Goods))
	if err != nil {
		return
	}

	// 监听端口
	listener, err := net.Listen("tcp", "localhost:9997")
	if err != nil {
		return
	}
	defer func(listener net.Listener) {
		err := listener.Close()
		if err != nil {

		}
	}(listener)

	for {
		fmt.Println("开始建立 rpc 连接")
		accept, err := listener.Accept()
		if err != nil {
			return
		}
		rpc.ServeConn(accept)
		fmt.Println("本次 rpc 调用结束")
	}
}
